/*
 *  Confidential and Proprietary                                                                
 Copyright 2008 By                                                                                     
 SGAI & Hewlett-Packard Development Company, L.P. 	              
 All Rights Reserved                                                                                  

 Project Name : SGAI  MES                                                                                                                                       
 Class Name   : IntegerConverter.java    
 Package      : com.hp.message.vo.converter          
 */
package com.erdos.message.vo.converter;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * Converts a int primitive or java.lang.Integer wrapper to a String.
 * if value is null, converts into an empty string; if string is empty, converts into a null Integer.
 @version     $Id: IntegerConverter.java 9110 2012-03-08 02:08:48Z hubin $                                                          
 @author sunf
 @since  2008-11-10 
 */
public class IntegerConverter implements Converter {

	@SuppressWarnings("unchecked")
	public boolean canConvert(Class type) {
		return type.equals(int.class) || type.equals(Integer.class);
	}

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		if(source==null || source.equals(Integer.MIN_VALUE)) {
			writer.setValue("");
		} else {
			writer.setValue(String.valueOf(source));
		}		
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		if(StringUtils.isNotBlank(reader.getValue())) {
			return Integer.valueOf(reader.getValue().trim(), 10);
		} else {
			return null;
		}		
	}

}
